// pages/order/send/send.js
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
     obj:{},
     address:'',
     code:'',
     wlno:'',
     showDate:false,
     wl:'',
     sendTime:'',
     dayNum:7,
     current: new Date().getTime(),
     minDate: new Date().getTime(),
     maxDate: new Date().getTime(),
     formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    },
     //显示的日期
     currentDateStr:util.timeFormatDayMin(new Date()),
    //明天日期
   // tomorrow:util.timeFormatDayHour (new Date(new Date().getTime()+ 24*60*60*1000)),
     arr:[],
     isshowwl:false,
     columns:[
       {id:1,label:'百世快递'},
       {id:2,label:'壹米滴答'}
     ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

     console.log(options.detail);
     this.setData({
      obj:JSON.parse(options.detail),
    });
    console.log(this.data.obj);
     //设置统计几天数据
     this.getBeforeDate();
  },

  //设置可选的最小日期
  getBeforeDate(){
    let rusult=util.countPrevDay(new Date(),this.data.dayNum);
    this.setData({ 
			minDate: rusult
		})
  },

  //确认开始时间
  onConfirmDate(e) { 
    this.setData({
      current: e.detail,
      currentDateStr:util.timeFormatDayMin(e.detail)
    })
    this.onCloseDate();
  },

 //隐藏开始时间
 onCloseDate(){
  this.setData({
    showDate: false
  })
},

  /**
   *
   * 显示物流公司列表
   */
  showLogisticsCompany:function(e){
    console.log(12);
    if(this.data.lcOpen){
      this.setData({
        lcOpen:false,
        lcShow:false,
        active:true,
      });
    } else {
      this.setData({
        content: this.data.logisticsCompany,
        lcOpen: true,
        lcShow: false,
        active: false,
      });
    }
  },

  //显示日期选择框
  onShowDate(){
    this.setData({ 
			showDate: true
		})
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  scan:function(){
    var that = this;
    wx.scanCode({
      success: (res) => {
        console.log(res);
         that.setData({code:res.result});
      }
    })
  },
  bindVal(e) {
    var that = this;
    console.log(that.data.detail);
  },
  scanBookingNote(e){
    var that = this;
    wx.scanCode({
      success: (res) => {
        console.log(res);
        that.setData({ wlno: res.result });
      }
    })
  },
  scanwl(e){
    var that = this;
    console.log(e);
    that.setData({
      wl: e.detail.value
    });
  },

  inputevent(e){
    var that = this;
    console.log(e);
    that.setData({
      wlno: e.detail.value
    });
  },
  scanEquipmentCode(e) {
    var that = this;
    let index=e.currentTarget.dataset.index;
    let bindex = e.currentTarget.dataset.bindex;
    wx.scanCode({
      success: (res) => {
        console.log(res);
        let datastr = 'detail.detailInfo[' + bindex +'].equipmentNo';
        that.setData({ [datastr]: res.result});
        console.log(that.data.detail.detailInfo);
      }
    })
  },
  checkboxChange(e){
    var that = this;
    console.log(e.detail);
    if(e.detail.value.length>0){
      that.setData({ isshowwl:true});
    }else{
      that.setData({ isshowwl:false,wl:null,wlno:null});
    }
    that.data.arr=[];
    e.detail.value.forEach(current => {
      this.data.obj.detail.forEach(item => {
          if(parseInt(current) == item.orderIndex){
            that.data.arr.push(item);
          }
      })
    })
    console.log(that.data.arr);
  },
  //扫描物联网定位设备码
  scanImei(e) {
    var that = this;
    let index = e.currentTarget.dataset.index;
    let bindex = e.currentTarget.dataset.bindex;
    wx.scanCode({
      success: (res) => {
        console.log(res);
        let datastr = 'detail.detailInfo[' + bindex + '].gpsno';
        that.setData({ [datastr]: res.result });
        console.log(that.data.detail.detailInfo);
      }
    })

  },
  submit(){
  
   console.log(this.data.obj);
   console.log(this.data.arr);
    //let sendEquipmentArr =[];
    if(this.data.arr == null || this.data.arr.length == 0){
      Toast.fail('请选择发货设备');
    }else{
      let flag = this.data.obj.detail.some(item=>{
        console.log(item.equipmentNo == null)
        return  item.equipmentNo == null
      })
      if(flag){
        Toast.fail('有没有绑物联网的设备，请先绑定再发货');
      }else{
        let logistic = {};
        if(this.data.wlno!='' && this.data.wlno != null &&  this.data.wl!= null && this.data.wl!=''){
          logistic.no = this.data.wlno;
          logistic.name = this.data.wl;
          logistic.sendTime = this.data.currentDateStr;
          console.log(logistic);
          //绑定完设备更新采购订单里面的状态
          //先根据订单id把订单查出来
          let param={
              isAuth:false,
              className:'send',
              data:{
                selectFields:["orderNo","relationOrderNo","detail","id","numbers","sendNumbers"],
                orderNo:this.data.obj.orderNo
              }
          }
        console.log(param);
        CommonService.goFindList(param).then(res=>{
          let sendNumbers=0;
          let sendEquipment=[];
          let sendid = null;
          if(res.data.data.result == null || res.data.data.result.length==0){
            this.data.arr.forEach(item1=>{
              this.data.obj.detail.forEach(item=>{
                if(item1.orderIndex == item.orderIndex){
                  item.logistic = logistic;
                  //sendEquipmentArr.push(item)
                }
              })
            })
            sendNumbers = this.data.obj.detail.length - this.data.arr.length;
            sendEquipment = this.data.obj.detail;
            sendid = null;
          }else{
            sendid = res.data.data.result[0].id
            console.log(res.data.data.result[0].id);
            this.data.arr.forEach(item1=>{
              res.data.data.result[0].detail.forEach(item=>{
                if(item1.orderIndex == item.orderIndex){
                  item.logistic = logistic;
                  //sendEquipmentArr.push(item)
                }
              })
            })
            sendNumbers =  res.data.data.result[0].numbers - this.data.arr.length;
            sendEquipment = res.data.data.result[0].detail;
          }
    
          let param = {
            className:'send',
            data:{
              id:sendid,
              relationOrderNo:this.data.obj.relationOrderNo,
              orderNo:this.data.obj.orderNo,
              detail:sendEquipment,
              numbers:sendNumbers
            }
          }
         // console.log("sendEquipmentArr");
          //console.log(sendEquipmentArr);
         
         CommonService.goSave(param).then(res=>{
           console.log(res);
           if(res.data.data.success){
              let purchaseParam = {
                className:'purchaseOrder',
                data:{
                  id:this.data.obj.id,
                  state:3,
                  sendNumbers:sendNumbers
                }
              }
               CommonService.goSave(purchaseParam).then(res1=>{
                 console.log(res1);
               })
    
              let classname = ""
              if(this.data.obj.businessType == 4){
                classname='tryOrder'
              }else{
                classname='order'
              }
    
              let param1 = {
                className:classname,
                data:{
                  id:this.data.obj.orderId,
                  state:3
                }
              }
               CommonService.goSave(param1).then(res1=>{
                 console.log(res1);
               })

               let param2 = {
                relationOrderNo:this.data.obj.relationOrderNo,
                sendGood:this.data.arr
              }
                CommonService.automaticSaveDeliveryPartsRecord(param2).then(res1=>{
                console.log(res1);
              })
              //试机订单发货不同步用友，转租赁/销售的时候再同步
              // if(this.data.obj.businessType != 4){
              //   this.yyInStorage(this.data.obj);
              // }
              //this.updatePurchaseEquipmentLogistic(sendEquipmentArr);

              //跳转页面
              //获取列表页对象
              let pages = getCurrentPages();
              let prevPage = pages[pages.length - 2];
              prevPage.refreshListAndPage();
              wx.navigateBack();
           }
          })
        })
        
        }else{
          Toast.fail('请选择发货设备，填写物流信息');
        }
      }
    }
  },
 
  //获取用友采购入库单参数
  yyInStorage(val){
    CommonService.yyInterfaces(val).then(res1=>{
      console.log(res1);
    })
  },

  //更新发货信息
  updatePurchaseEquipmentLogistic(sendEquipmentArr){
    CommonService.updatePurchaseEquipmentLogistic({"data":sendEquipmentArr}).then(res1=>{
      console.log(res1);
    })
  },
  

  onChange(e){
    console.log(e.detail);
    var that = this;

    that.setData({});
  }
})